package lunify;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Reads from files. Necessary when Scanner goes awry and file io is needed.
 * @author Katie
 * @version 1.0
 */
public class FReader {

    private int counter;
    private BufferedReader reader;
    private String line;
    private String file;

    /**
     * Opens a stream to the specified file. Use isOK() to test success; no file not found exceptions will be thrown here.
     * @param fname
     */
    public FReader(String fname) {
        file = fname;
        try {
            reader = new BufferedReader(new FileReader(fname));
            counter = 0;
            line = null;
        } catch (FileNotFoundException ex) {
            line = null;
            reader = null;
        }
    }

    /**
     * Tests whether the stream to the file has been opened successfully.
     * @return true iff the stream is opened and ready to read from
     */
    public boolean isOK(){
        return reader!=null;
    }

    /**
     * Reads the next line in the file. Will return null if the stream is, or suddenly becomes, broken.
     * @return the next line
     */
    public String nextLine() {
        if (reader == null) {
            return null;
        }
        try {
            line = reader.readLine();
            counter++;
        } catch (IOException ex) {
            line = null;
            reader = null;
        }
        return line;
    }

    /**
     * Returns the latest line fetched by nextLine();
     * @return
     */
    public String currentLine(){
        return line;
    }

    /**
     * Returns the number of lines read (useful for debugging).
     * @return
     */
    public int linesRead() {
        return counter;
    }

    /**
     * Resets the connection to this file.
     * @return true iff a new valid connection with the originally-specified file has been successfully established.
     */
    public boolean reset() {
        if (reader == null) {
            stop();
        }
        try {
            reader = new BufferedReader(new FileReader(file));
            counter = 0;
            return true;
        } catch (FileNotFoundException ex) {
            return false;
        }
    }

    /**
     * Severs the stream.
     * @return
     */
    public boolean stop() {
        if (reader == null) {
            return false;
        }
        try {
            reader.close();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }
}